package com.ttsx.service.impl;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradePagePayModel;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ttsx.core.common.constant.AlipayConstants;
import com.ttsx.core.common.enums.OrderStatusEnum;
import com.ttsx.core.common.enums.PayStatusEnum;
import com.ttsx.core.common.enums.PayTypeEnum;
import com.ttsx.core.common.exception.TTSXException;
import com.ttsx.mapper.PaymentMapper;
import com.ttsx.pojo.dto.payment.PaymentQueryDTO;
import com.ttsx.pojo.entity.Order;
import com.ttsx.pojo.entity.Payment;
import com.ttsx.service.OrderService;
import com.ttsx.service.PaymentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author lucky
 * @description 针对表【ttsx_payment(支付表)】的数据库操作Service实现
 * @createDate 2025-03-04 16:58:06
 */
@Service
public class PaymentServiceImpl extends ServiceImpl<PaymentMapper, Payment>
        implements PaymentService {

    @Lazy
    @Autowired
    private OrderService orderService;


    @Override
    public PageInfo<Payment> getPage(Integer pIndex, Integer pSize, PaymentQueryDTO paymentQueryDTO) {

        PageHelper.startPage(pIndex, pSize);

        Integer payMethod = paymentQueryDTO.getPayMethod();

        LambdaQueryWrapper<Payment> lqw = new LambdaQueryWrapper<>();
        lqw.eq(payMethod != null, Payment::getPayMethod, payMethod);

        lqw.orderByDesc(Payment::getCreateTime);

        List<Payment> payments = baseMapper.selectList(lqw);

        return new PageInfo<>(payments, 5);
    }

    @Override
    public void updateStatus(String outTradeNo, String tradeNo) {
        // 更新支付状态
        Payment payment = getByOrderNo(outTradeNo);
        payment.setPayStatus(PayStatusEnum.PAID.getCode());
        payment.setPayTime(LocalDateTime.now());
        payment.setTradeNo(tradeNo);
        baseMapper.updateById(payment);

        // 更新订单状态
        Order order = orderService.getByOrderNo(outTradeNo);
        order.setOrderStatus(OrderStatusEnum.UNSHIPPED.getCode());
        orderService.updateById(order);
    }

    @Override
    public Payment getByOrderNo(String orderNo) {
        LambdaQueryWrapper<Payment> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Payment::getOrderNo, orderNo);
        return baseMapper.selectOne(lqw);
    }

    public AlipayTradePagePayResponse createPay(Order order, Integer payMethod) {
        if (ObjectUtil.equal(payMethod, PayTypeEnum.ALIPAY.getCode())) {
            // 创建支付宝客户端
            AlipayClient alipayClient = new DefaultAlipayClient(
                    AlipayConstants.GATEWAY_URL,
                    AlipayConstants.APP_ID,
                    AlipayConstants.PRIVATE_KEY,
                    "json",
                    AlipayConstants.CHARSET,
                    AlipayConstants.PUBLIC_KEY,
                    AlipayConstants.SIGN_TYPE
            );

            // 创建支付请求
            AlipayTradePagePayRequest payRequest = new AlipayTradePagePayRequest();
            payRequest.setReturnUrl(AlipayConstants.RETURN_URL);
            payRequest.setNotifyUrl(AlipayConstants.NOTIFY_URL);

            // 创建订单信息
            AlipayTradePagePayModel model = new AlipayTradePagePayModel();
            model.setOutTradeNo(order.getOrderNo());
            model.setTotalAmount(order.getTotalAmount().toString());
            model.setSubject("天天生鲜商城购物订单");
            model.setProductCode("FAST_INSTANT_TRADE_PAY");
            //model.setQrPayMode("1");
            model.setQrcodeWidth(100L);
            model.setTimeExpire(LocalDateTimeUtil.format(
                    LocalDateTime.now().plusMinutes(15), "yyyy-MM-dd HH:mm:ss"));

            payRequest.setBizModel(model);
            try {
                return alipayClient.pageExecute(payRequest);
            } catch (AlipayApiException e) {
                throw new TTSXException("支付请求创建失败");
            }
        }

        return null;
    }

}




